import React, { PureComponent } from 'react';
import { Modal, Alert, Tag, Spin, Checkbox, Row, Col } from 'antd';
// import { connect } from 'dva';
import lodash from 'lodash';
// import PageHeaderLayout from '../../layouts/PageHeaderLayout';
// import Ellipsis from '../../components/Ellipsis';
import { cutOffStr } from '../../utils/utils';
import { findSysNameByUser } from '../../services/manage-by-query-controller';
// import classNames from 'classnames';
import styles from './UserBindSysName.less';

// 初始状态
const InitState = {
  // 查询状态
  queryLoading: false,
  // 当前选择的用户
  selectUser: undefined,
  // 当前选择用户已经绑定的系统列表
  selectUserSys: [],
  // 选中的系统列表
  selectSysNameList: [],
}

// @Form.create()
export default class UserBindSysName extends PureComponent {

  state = {
    ...InitState,
  }

  // 重置状态
  resetState = () => {
    this.setState(InitState);
  }

  // 初始化现实化数据
  initVisibleData = (userList) => {
    // const { userList } = this.props;
    if (userList && userList.length === 1) {
      // 当 userList.length===1时 设置 selectSysNameList 为用户当前已经绑定了的系统
      this.setState({ queryLoading: true });
      findSysNameByUser(userList[0].username).then(selectUserSys => {
        this.setState({ queryLoading: false, selectSysNameList: selectUserSys })
      }).catch(() => this.setState({ queryLoading: false }));
    }
  }

  // 选择的用户 DIV
  getSelectUserDiv = (userList) => {
    const { selectUser } = this.state;
    const { delSelectUser } = this.props;
    const color = '#108ee9';
    const marginBottom = 12;
    const fontSize = 14;
    // 未选择用户
    if (!userList || userList.length <= 0) {
      return <Alert message="当前没有选择用户，请选择用户！" type="error" closable={false} />;
    }
    // 选择一个用户
    if (userList.length === 1) {
      return (
        <div style={{ marginTop: 6, marginBottom: -6 }}>
          <span style={{ marginLeft: 6, fontSize }}>当前选择的用户：</span>
          <span style={{ color, fontSize }}>{userList[0].username}</span>
        </div>
      );
    }
    // 选择多个用户
    return (
      <div className={styles.divBox}>
        <div className={styles.divBoxTitle}>选择用户</div>
        <Tag
          style={{ marginBottom, fontSize }}
          color={selectUser ? undefined : color}
          onClick={() => this.setState({ selectUser: undefined, selectUserSys: [] })}
          visible={true}
        >
          统一分配
        </Tag>
        {userList.map(user => (
          <Tag
            style={{ marginBottom, fontSize }}
            key={user.id}
            color={user.username === selectUser ? color : undefined}
            visible={true}
            closable={userList.length > 1}
            onClick={e => {
              if (e && e.target && e.target.tagName && lodash.toUpper(e.target.tagName) === "DIV") {
                this.selectUserChange(user.username);
              }
            }}
            onClose={() => {
              if (delSelectUser instanceof Function) {
                delSelectUser(user.id);
                if (user.username === selectUser) {
                  this.setState({ selectUser: undefined, selectUserSys: [] });
                }
              }
            }}
          >
            {user.username}
            {/* <span onClick={() => this.selectUserChange(user.username)}>{user.username}</span> */}
          </Tag>
        ))}
      </div>
    );
  }

  // 选择的用户变化
  selectUserChange = (username) => {
    const { selectUser } = this.state;
    if (selectUser === username) return;
    this.setState({ queryLoading: true, selectUser: username });
    findSysNameByUser(username).then(selectUserSys => {
      this.setState({ queryLoading: false, selectUserSys });
    }).catch(() => this.setState({ queryLoading: false, selectUser }));
  }

  // 选择的系统 DIV
  getSysNamesDiv = (userList, sysNameList) => {
    const { queryLoading, selectUser, selectUserSys, selectSysNameList } = this.state;
    // const marginBottom = 12;
    let canSelectSysName = false;
    // 只选择了一个用户 或者 选择了多个用户而且没有选中用户 ---- 才能选择系统
    if (userList.length === 1 || (userList.length > 1 && !selectUser)) {
      canSelectSysName = true;
    }
    return (
      <Spin delay={300} spinning={queryLoading}>
        <div className={styles.divBox} style={{ minHeight: 150 }}>
          <div className={styles.divBoxTitle}>选择分配系统</div>
          <Checkbox.Group
            style={{ width: '100%' }}
            value={canSelectSysName ? selectSysNameList : selectUserSys}
            onChange={checkedValue => {
              if (canSelectSysName) {
                this.setState({ selectSysNameList: checkedValue });
              }
            }}
          >
            <Row>
              {sysNameList.map(sysName => {
                const lable = cutOffStr(sysName, 14);
                return (
                  <Col span={6} key={sysName}>
                    <Checkbox value={sysName}>
                      {lable === sysName ? sysName : <span title={sysName}>{lable}</span>}
                    </Checkbox>
                  </Col>
                );
              })}
            </Row>
          </Checkbox.Group>
        </div>
      </Spin>
    );
  }

  // 确定
  onCreate = () => {
    const { selectSysNameList } = this.state;
    const { onOk, userList } = this.props;
    if (onOk instanceof Function) {
      onOk(userList.map(user => user.username), selectSysNameList);
    }
  }

  render() {
    const { userList, sysNameList, resetStateFuc, initVisibleDataFuc, visible, confirmLoading, onCancel } = this.props;
    // const { getFieldDecorator, getFieldValue } = form;
    if (resetStateFuc instanceof Function) resetStateFuc(this.resetState);
    if (initVisibleDataFuc instanceof Function) initVisibleDataFuc(this.initVisibleData);
    // const width = 200;
    return (
      <Modal
        width={670}
        visible={visible}
        confirmLoading={confirmLoading}
        title="为用户分配系统"
        okText="确定"
        onCancel={onCancel}
        onOk={this.onCreate}
        maskClosable={false}
        bodyStyle={{ padding: '8px 12px 0 12px' }}
      >
        {(userList && userList.length > 1) ? <Alert message={`已选择${userList.length}个账户，这些账户将会重置绑定的系统`} type="warning" closable={false} /> : ''}
        {this.getSelectUserDiv(userList)}
        {this.getSysNamesDiv(userList, sysNameList)}
      </Modal>
    );
  }
}
